﻿using System;
using System.Collections.Generic;
using System.Linq;
using Myotragus.Data.Domain;
using Myotragus.Data.Metadata;
using Myotragus.Data.Util;

namespace Myotragus.Data.Emit
{
	public class SaveEntityGenerator : LocalizableOperationEntityGenerator, ISaveEntityGenerator
	{
		protected static readonly Type TypeOfLocalizableText = typeof(LocalizableText);

		public SaveEntityGenerator(IDynamicAssembly dynamicAssembly, INameGenerator nameGenerator,
			ILocalizableEntityMapping mapping)
			: base(dynamicAssembly, nameGenerator, mapping)
		{
		}

		protected override IEnumerable<Type> CreateBaseEntityInterfaces(IEnumerable<Type> interfaces)
		{
			var interfacesCopy = interfaces.ToList();
			var id = FindIdProperty(interfacesCopy);
			return interfacesCopy.Where(i => TypeOfIEntity.IsAssignableFrom(i))
				.Select(i => BaseInterfaceType.MakeGenericType(i, id.PropertyType));
		}

		protected static readonly Type TypeOfISaveEntity = typeof(ISaveEntity<,>);

		protected override Type BaseInterfaceType
		{
			get { return TypeOfISaveEntity; }
		}

		protected override void AttachLocalizableProperty(IDynamicType type, string propertyName)
		{
			type.DefineAutomaticProperty(propertyName, TypeOfLocalizableText);
		}
	}
}